﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IMS_Data;
using System.Transactions;

namespace IMS_WEB
{
    
    public partial class updateProductStatus : System.Web.UI.Page
    {
        string contract_sn = "";
        private string btnDelPrefix = "btnDel_";
        private string tbPrefix = "tb_";
        order m_od = null;

        enum DisplayMode { View, Update };

        private DisplayMode displayMode = DisplayMode.Update;
        private void ReloadUpdateUI( )
        {
            if (!string.IsNullOrEmpty(contract_sn))
            {
                OrderReposity or = new OrderReposity();

                m_od = or.GetOrderByID(contract_sn);

                tbAccount.Text = m_od.contract_account;
                tbAddress.Text = "";
                tbCompany.Text = m_od.contract_supplier;

                tbPhone.Text = m_od.contract_contactPhone;
                tbSN.Text = m_od.contract_sn;
                tbTax.Text = m_od.contract_taxsn;
                int i = 1;
                foreach (var ele in m_od.orderDetail)
                {

                    TableRow tr = CreateRowControl(i, ele);
                    if (tr != null)
                    {
                        Table1.Rows.Add(tr);
                    }
                    i++;

                }
                if (m_od.contract_status == CommonData.OrderInCheck)
                {
                    btnUpdateStatus.Enabled = false;
                }
            }
        }

        private void ReloadViewUI()
        {
            if (!string.IsNullOrEmpty(contract_sn))
            {
                OrderReposity or = new OrderReposity();
                CompanyReposity cr = new CompanyReposity();
                

                m_od = or.GetOrderByID(contract_sn);

                tbAccount.Text = m_od.contract_account;
                tbAccount.Enabled = false;

                tbCompany.Text = m_od.contract_supplier;
                tbCompany.Enabled = false;

                company cpy = cr.GetCompany(m_od.contract_supplier);
                if (cpy != null)
                {
                    tbAddress.Text = cpy.company_address;
                    tbAddress.Enabled = false;
                }

                tbPhone.Text = m_od.contract_contactPhone;
                tbPhone.Enabled = false;

                tbSN.Text = m_od.contract_sn;
                tbSN.Enabled = false;

                tbTax.Text = m_od.contract_taxsn;
                tbTax.Enabled = false;

                int i = 1;
                foreach (var ele in m_od.orderDetail)
                {

                    TableRow tr = CreateRowControl(i, ele);
                    if (tr != null)
                    {
                        Table1.Rows.Add(tr);
                    }
                    i++;

                }
                
                btnUpdateStatus.Visible = false;
                btnAudit.Visible = false;
                
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            contract_sn = Request.QueryString["ID"];
            if (!string.IsNullOrEmpty(contract_sn))
            {
                displayMode = DisplayMode.Update;
                ReloadUpdateUI();
            }
            else
            {
                contract_sn = Request.QueryString["contract_sn"];
                if (!string.IsNullOrEmpty(contract_sn))
                {
                    displayMode = DisplayMode.View;
                    ReloadViewUI();
                }
            } 
        }

        private int GetIndexByString(DropDownList list, string str)
        {
            int index = 0;

            ListItem item = list.Items.FindByText(str);
            if (item != null)
            {
                index = list.Items.IndexOf(item);
            }

            return index;
        }

        private TableRow CreateRowControl(int rowIndex, orderDetail detail)
        {
            TableRow row = new TableRow();
            Unit[] sizes = new Unit[] { 
                Unit.Pixel(50),
                Unit.Pixel(150), 
                Unit.Pixel(150), 
                Unit.Pixel(80), 
                Unit.Pixel(80), 
                Unit.Pixel(80)};
            string[] values = new string[]
            { 
                rowIndex.ToString(),
                detail.product.product_code.Trim(),
                detail.product.product_name.Trim(),
                detail.product.product_type.Trim(),
                detail.product.product_unit.Trim(),
                //detail.product.product_salePrice.ToString(),

            };

            for (int j = 1; j <= values.Length - 1; j++)
            {
                TableCell cell = new TableCell();
                Label box = new Label();
                box.Text = values[j - 1];
                box.Width = sizes[j - 1];
                box.ID = tbPrefix + rowIndex.ToString() + j.ToString();
                cell.Controls.Add(box);
                row.Cells.Add(cell);

            }
            TableCell cellPrice = new TableCell();
            TextBox tbPrice = new TextBox();
            if (displayMode == DisplayMode.View)
            {
                tbPrice.Enabled = false;
            }
            tbPrice.Text = values[values.Length - 1];
            tbPrice.Width = sizes[values.Length - 1];
            tbPrice.ID = tbPrefix + rowIndex.ToString() + values.Length.ToString();
            cellPrice.Controls.Add(tbPrice);
            row.Cells.Add(cellPrice);

            DropDownList statusList = new DropDownList();

            if (displayMode == DisplayMode.View)
            {
                statusList.Enabled = false;
            }
            statusList.Items.Add(CommonData.OrderInRecvProduct);
            statusList.Items.Add(CommonData.OrderInPay);
            statusList.Items.Add(CommonData.OrderInOver);
            
            statusList.SelectedIndex = GetIndexByString(statusList,detail.product_status);
            statusList.ID = btnDelPrefix + rowIndex.ToString();
            TableCell cellDel = new TableCell();
            cellDel.Text = detail.index_id.ToString();
            cellDel.Controls.Add(statusList);
            row.Cells.Add(cellDel);
            return row;
        }

        private void UpdateDetailStatus(int index, string status)
        {
            foreach (var ele in m_od.orderDetail)
            {
                if (ele.index_id == index)
                {
                    ele.product_status = status;

                    using (IMS_Data.IMS_DBEntities ctx = new IMS_Data.IMS_DBEntities())
                    {

                        ctx.orderDetail.Attach(ele);

                        var entryState = ctx.ObjectStateManager.GetObjectStateEntry(ele);
                        entryState.SetModifiedProperty("product_status");
                        ctx.SaveChanges();
                        break;
                    }
                }
            }
        }

        private void UpdateDetailPriceAndStatus(int index, double price, string status)
        {
            foreach (var ele in m_od.orderDetail)
            {
                if (ele.index_id == index)
                {
                    //ele.product.product_salePrice = (Decimal)price;
                    ele.product_status = status;
                    ele.order.contract_status = status;

                    using (IMS_Data.IMS_DBEntities ctx = new IMS_Data.IMS_DBEntities())
                    {
                        ctx.product.Attach(ele.product);

                        var entryPrice = ctx.ObjectStateManager.GetObjectStateEntry(ele.product);
                        entryPrice.SetModifiedProperty("product_salePrice");
                        ctx.SaveChanges();

                        ctx.order.Attach(ele.order);

                        var entryOrder = ctx.ObjectStateManager.GetObjectStateEntry(ele.order);
                        entryOrder.SetModifiedProperty("contract_status");
                        ctx.SaveChanges();

                        ctx.orderDetail.Attach(ele);
                        var entryState = ctx.ObjectStateManager.GetObjectStateEntry(ele);
                        entryState.SetModifiedProperty("product_status");
                        ctx.SaveChanges();
                        break;
                    }
                }
            }
        }

        protected void btnUpdateStatus_Click(object sender, EventArgs e)
        {
            int rowIndex = 0;
            using (var ts = new TransactionScope())
            {
                foreach (TableRow ele in Table1.Rows)
                {
                    if (rowIndex == 0)
                    {
                        rowIndex++;
                        continue;
                    }
                    TableCell tc = ele.Cells[ele.Cells.Count - 1];

                    int index = Convert.ToInt32(tc.Text);

                    DropDownList statusList = (DropDownList)tc.FindControl(btnDelPrefix + rowIndex.ToString());

                    string status = statusList.SelectedItem.Text;

                    UpdateDetailStatus(index, status);

                    rowIndex++;
                }
                
                ts.Complete();
            }
            Response.Write("<script>alert('更新订单状态成功')</script>");
        }

        protected void Button5_Click(object sender, EventArgs e)
        {
            int rowIndex = 0;
            using (var ts = new TransactionScope())
            {
                foreach (TableRow ele in Table1.Rows)
                {
                    if (rowIndex == 0)
                    {
                        rowIndex++;
                        continue;
                    }
                    TableCell tc = ele.Cells[ele.Cells.Count - 2];

                    int index = Convert.ToInt32(ele.Cells[ele.Cells.Count - 1].Text);

                    TextBox tbPrice = (TextBox)tc.FindControl(tbPrefix + rowIndex.ToString() + (ele.Cells.Count - 1).ToString());

                    string status = CommonData.OrderInSendProduct;

                    UpdateDetailPriceAndStatus(index, Convert.ToDouble(tbPrice.Text), status);

                    rowIndex++;
                }
                ts.Complete();
            }
            Response.Write("<script>alert('订单审核成功')</script>");
            
        }
    }
}